Skip to content

Transform small blocks by a plain loop in the CPU add_transform! - #626

Draft
leburgel wants to merge 3 commits into
mainfrom
lb/cpu_small_subblocks
Draft

leburgel wants to merge 3 commits into
mainfrom
lb/cpu_small_subblocks

Conversation

@leburgel

Copy link
Copy Markdown
Member

Alternative to #597 that gets most of the speedup without caching anything in the tree transformers.

On the CPU, permute, braid, transpose and twist call tensoradd! once per fusion-tree subblock, which costs about 0.3 µs per call independent of the subblock size. For tensors with many small subblocks, such as fermionic U(1)-symmetric PEPS tensors, this dominates: permute! becomes up to 100× slower than copying the data.

#597 removes that overhead by collecting the small subblocks into groups with cached index lists. This PR instead adds a single method of _add_transform_block! for the StridedSubblocks of CPU TensorMaps: blocks with at most 1024 entries to compute (length(U) * prod(sz)) are transformed term by term with a plain loop over the flat data, addressed through the (size, strides, offset) structure that the transformer already holds. Larger blocks take the same path as before. There is no new type, no new field in the transformers and no extra cached data, and the threaded and GPU paths are untouched. taskforeach also skips its atomic counter for a single worker, which was a measurable part of the per-subblock cost.

permute! into a preallocated destination, one thread, best of 30, in ms (p = ((1, 4, 2), (5, 3, 6)) on Vχ ⊗ VD ⊗ VD' ← Vχ ⊗ VD ⊗ VD'), the same cases as in #597, all three versions measured on the same machine:

sector, legs subblocks largest copy! main #597 this PR
fℤ₂ × U(1), Vχ charges ±2, deg. 4; VD ±1, deg. 1 9632 16 0.100 2.70–2.72 0.154–0.175 0.425–0.434
fℤ₂ × U(1), Vχ charges ±8, deg. 2; VD ±1, deg. 1 40736 4 0.106 11.54–11.59 0.206 1.36–1.38
U(1), Vχ charges ±2, deg. 16; VD ±1, deg. 1 301 256 0.049 0.129 0.065–0.073 0.065–0.066
U(1), Vχ charges ±2, deg. 32; VD ±1, deg. 2 301 16384 3.87 6.85–6.86 6.83–6.88 6.83–6.87
SU(2), Vχ j ≤ 1, deg. 2; VD j ≤ 1/2, deg. 1 120 4 0.000 0.067–0.068 0.002 0.009
SU(2), Vχ j ≤ 1, deg. 16; VD j ≤ 1/2, deg. 2 120 4096 0.33 1.36–1.37 1.37–1.38 1.37
fℤ₂ × SU(2), j ≤ 1, deg. 2 / 1 977 4 0.001 0.595–0.609 0.014 0.102–0.103
fℤ₂ × SU(2), j ≤ 1, deg. 4 / 2 977 256 0.163 1.29–1.30 0.698–0.704 1.14–1.25

Ranges are over two runs. Compared to #597:

The existing permutation tests only have small subblocks, so I added a testset with blocks on both sides of the threshold, which also covers nonzero β and an adjoint source.

Benchmark script
using TensorKit
besttime(f) = (f(); minimum(_ -> @elapsed(f()), 1:30))
fU1(qmax, d) = Vect[FermionParity ⊠ U1Irrep]([(p, q) => d for p in 0:1 for q in -qmax:qmax]...)
U1(qmax, d) = U1Space([q => d for q in -qmax:qmax]...)
SU2(jmax, d) = SU2Space([j => d for j in 0:1//2:jmax]...)
fSU2(jmax, d) = Vect[FermionParity ⊠ SU2Irrep]([(isodd(2j), j) => d for j in 0:1//2:jmax]...)
cases = [
    (fU1(2, 4), fU1(1, 1)), (fU1(8, 2), fU1(1, 1)),
    (U1(2, 16), U1(1, 1)), (U1(2, 32), U1(1, 2)),
    (SU2(1, 2), SU2(1 // 2, 1)), (SU2(1, 16), SU2(1 // 2, 2)),
    (fSU2(1, 2), fSU2(1, 1)), (fSU2(1, 4), fSU2(1, 2)),
]
p = ((1, 4, 2), (5, 3, 6))
for (Vχ, VD) in cases
    t = randn(ComplexF64, Vχ ⊗ VD ⊗ VD' ← Vχ ⊗ VD ⊗ VD')
    tdst, tcopy = permute(t, p; copy = true), similar(t)
    println(
        length(fusiontrees(t)), " subblocks, largest ", maximum(length ∘ last, subblocks(t)),
        ": copy! ", round(1.0e3 * besttime(() -> copy!(tcopy, t)); digits = 3),
        " ms, permute! ", round(1.0e3 * besttime(() -> permute!(tdst, t, p)); digits = 3), " ms"
    )
end

🤖 Generated with Claude Code

On the CPU, `permute`, `braid`, `transpose` and `twist` call `tensoradd!` once per subblock (and `mul!` once per multi-tree block), whose call overhead dominates for tensors with many small subblocks. Blocks of a `TensorMap` with at most 1024 entries to compute are now transformed term by term with a plain loop over the flat data, addressed directly through the cached subblock structure. Nothing is added to the tree transformers.

`taskforeach` skips the atomic counter for a single worker.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@leburgel
leburgel requested a review from lkdvos November 18, 2026 12:35
end

# computes `A = β * A + α * permutedims(op.(B), p)` for the strided arrays `A` and `B` within `a` and `b`
function _add_strided!(a, b, (sz, strides_dst, offset_dst), (_, strides_src, offset_src), p, op::F, α, β) where {F}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this compare to actually forming the StridedView and doing a broadcasting expression on that?
It might actually make sense to fix this "higher up", ie just make Strided.jl bypass all its optimizations/blocking/... when the number of entries is below 1024. The main question is a bit which part of the tensoradd! stack actually adds all the overhead, and whether or not we can get rid of it.

This is mostly what I was trying to do before, but definitely did not go into a lot of detail on that. (As a side comment, can you double-check you are comparing to the latest versions of Strided-TensorOperations, since some of the improvements did actually make it in)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked, and this was all tested using the latest versions of everything at the time: Strided 2.6.7 (so with #87–#92 and #97), StridedViews 0.5.5, TensorOperations 5.8.4. StridedViews had a new release since, but that shouldn't affect the timings here.

For a 4-entry, 6-index ComplexF64 block, one tensoradd! call costs about 220 ns on my workstation, against about 20 ns for the loop. Forming the StridedView is ~1 ns, and broadcasting on it costs the same as tensoradd!, so it is not the TensorOperations wrapper (under 10% of the profile). About 60% of the samples are in _mapreduce_order! → order_and_fuse_dims (_fusedims, indexorder, the cost computation), and ~11% in the kernel itself.

I also tried out QuantumKitHub/Strided.jl#99, cherry-picked onto main, plus stridedtensoradd! calling the new permutedims!, so that TensorKit main picks it up unchanged. On top of that I added a plain loop nest for at most 32 elements that skips the sorting and fusing. permute! in ms on a shared, loaded machine (not the workstation, so only the ratios mean something; minimum over 8 interleaved runs):

subblocks / largest main main + Strided#99 main + Strided#99 + loop this PR
9632 / 16 (fℤ₂ ⊠ U1) 5.65 3.48 1.62 0.92
40736 / 4 (fℤ₂ ⊠ U1) 26.9 18.7 12.0 7.15
301 / 256 (U1) 0.32 0.21 0.23 0.14
977 / 4 (fℤ₂ ⊠ SU2) 1.14 0.65 0.59 0.18
977 / 256 (fℤ₂ ⊠ SU2) 2.49 2.25 2.35 2.69
301 / 16384 (U1) 17.5 17.2 18.1 17.4

So for Abelian symmetries with tiny blocks a Strided-side fix recovers most of it (75–85% of the time this PR saves), and it helps everything else that calls tensoradd! on small arrays. It doesn't cover the non-Abelian case, where the remaining time is the per-block recoupling and not the permutation.

One way forward would be to keep this PR for the small blocks, get the small path into Strided, and then lower the 1024 cutoff here to whatever the Strided path does not already handle well. Above ~256 entries the Strided kernel is already as fast as the loop, and faster for β ≠ 0 on complex data, so the cutoff here can probably come down quite a bit.

Comment on lines +813 to +822
# calls `f(i, j)` for the positions of all corresponding entries of two strided arrays of size `sz`
@inline _stridedloop(f, ::Tuple{}, ::Tuple{}, ::Tuple{}, i::Int, j::Int) = f(i, j)
@inline function _stridedloop(f, sz::Tuple, strides₁::Tuple, strides₂::Tuple, i::Int, j::Int)
for _ in 1:last(sz)
_stridedloop(f, Base.front(sz), Base.front(strides₁), Base.front(strides₂), i, j)
i += last(strides₁)
j += last(strides₂)
end
return nothing
end

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is actually quite a cool code pattern, I wonder if it could be used to replace some of the @generated functions in the Strided kernels. In particular, something I always wondered about is whether this could be used to reduce the compilation time a bit, for example by only inlining the first N layers and then actually using a function call. (This is definitely something Claude can play around with rather quickly/efficiently 😉)

Ultimately, I do think it reads a lot nicer than the actual generated functions so that would also be a bonus.

@Jutho tagging you here explicitly, since this might be of interest to you 😄

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes this looks very cool indeed.
As an aside, I hope to finally have a proper chunk of time for PR reviews the next few days.

Comment thread src/auxiliary/auxiliary.jl Resolved
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
dst::StridedSubblocks{<:CPUStorage}, src::StridedSubblocks{<:CPUStorage}, p, conjsrc::Bool,
U, inds_dst, inds_src, buffer, α, β, backend, allocator
)
if length(U) * prod(first(@inbounds src.structure[first(inds_src)])) > SMALL_BLOCK_LENGTH

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is actually quite a good point, and somewhat independent of the strided kernel:
I think currently the recoupling step that uses the buffer only ever checks the size of U being 1x1, while arguably things like 2x2 still don't benefit from the BLAS call: every input has to be copied twice anyways, so the gain from the BLAS intermediate accessing memory more efficiently is completely not there. Ultimately, I think to get optimal performance it would be nice to get a custom kernel for the recoupling as a whole, which does something like QuasiStrided.jl but then for "lists of inputs" rather than just regular strided inputs. If someone has some tokens to burn and/or compute to do this it might still speed up things by quite a lot, also for the larger cases, but 🤷

…in _add_strided!

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants